package com.desaweb.pe.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.desaweb.pe.data.DatabaseManager;
import com.desaweb.pe.form.ServicioForm;
import com.desaweb.pe.form.UsuarioForm;

/**
 * Servlet implementation class UsuarioServlet
 */
public class UsuarioServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String ACTIVE_MENU="menu_usuario";
	private static final String FORM_PAGE="/pages/usuario/formulario.jsp";
	private static final String LIST_PAGE="/pages/usuario/consulta.jsp";   
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UsuarioServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setAttribute("active_menu", ACTIVE_MENU);
		String template = request.getParameter("template");
	
		RequestDispatcher view = null ;
		if(template.equalsIgnoreCase("consulta")){
			request.setAttribute("usuarios", DatabaseManager.getInstance().obtenerUsuarios());
			view = request.getRequestDispatcher(LIST_PAGE);
			
		}else if(template.equalsIgnoreCase("registro")){
			initForm(request);
			
			view = request.getRequestDispatcher(FORM_PAGE);
		}
		view.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	private void initForm(HttpServletRequest request){
		String paramId=request.getParameter("param");
		UsuarioForm usuarioForm = new UsuarioForm();
		if(paramId !=null){
			usuarioForm.populateForm(DatabaseManager.getInstance().obtenerUsuario(Integer.parseInt(paramId)));
		}
		request.setAttribute("usuarioForm", usuarioForm);
	}
	

}
